import {defineStore} from 'pinia';
import {ref} from 'vue';

export const useUserStore = defineStore(
    'user',
    () => {

        // 用户信息
        const id = ref(null)
        const nickname = ref(null)
        const email = ref(null)
        const photo = ref(null)
        const role = ref(null)
        const registerTime = ref(null)

        /**
         * 计算头像
         */
        const avatar = computed(() => {
            if (photo.value) {
                return photo.value
            } else {
                return "https://img.loliapi.cn/i/pp/img159.webp"
            }
        })

        const setUserInfo = (newId, newNickname, newEmail, newPhoto, newRole, newRegisterTime) => {
            id.value = newId
            nickname.value = newNickname
            email.value = newEmail
            photo.value = newPhoto
            role.value = newRole
            registerTime.value = newRegisterTime
        }

        const clearUserInfo = () => {
            id.value = null
            nickname.value = null
            email.value = null
            photo.value = null
            role.value = null
            registerTime.value = null
        }

        const updateAvatar = (newPhoto) => {
            photo.value = newPhoto
        }

        return {
            id,
            nickname,
            email,
            photo,
            role,
            registerTime,
            setUserInfo,
            avatar,
            clearUserInfo,
            updateAvatar
        }
    },
    {
        persist: {
            storage: localStorage
        }
    }
)
